import 'dart:convert';

import 'package:bot_toast/bot_toast.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:fluro/fluro.dart';
import 'package:flutter/material.dart';
import 'package:flutter_chip/bean/GdsMsg.dart';
import 'package:flutter_chip/bean/Goods.dart';
import 'package:flutter_chip/bean/User.dart';
import 'package:flutter_chip/config/Api.dart';
import 'package:flutter_chip/config/Comm.dart';
import 'package:flutter_chip/config/Http.dart';
import 'package:flutter_chip/config/Routers.dart';
import 'package:flutter_chip/utils/comm_utils.dart';
import 'package:flutter_chip/utils/toast_utils.dart';
import 'package:flutter_chip/widget/RouteSlide.dart';
import 'package:flutter_chip/widget/view_image.dart';
import 'package:flutter_chip/widget/widget_comm.dart';
import 'package:provide/provide.dart';

class GoodsInfoPage extends StatefulWidget {
  final String goodsId;

  const GoodsInfoPage({Key key, this.goodsId}) : super(key: key);

  @override
  _GoodsInfoPageState createState() => _GoodsInfoPageState();
}

class _GoodsInfoPageState extends State<GoodsInfoPage> {
  var _item = [];
  var _isEdit = false;
  var textController = TextEditingController();
  Goods goods;
  bool _isSelf = false;
  User user;

  @override
  void initState() {
    super.initState();
    _getGoods();
    _getReply();
  }

  @override
  Widget build(BuildContext context) {
    user = Provide.value<User>(context);
    return Scaffold(
      body: GestureDetector(
          child: Column(children: <Widget>[
            Expanded(
              child: NestedScrollView(
                headerSliverBuilder: _headerSliver,
                body: Container(),
              ),
            ),
            _isEdit ? _showSendWidget() : _bottomSheet()
          ]),
          onTap: () {
            setState(() {
              if (_isEdit) {
                _isEdit = false;
              }
            });
          }),
    );
  }

  List<Widget> _headerSliver(BuildContext context, bool innerBoxIsScrolled) {
    return <Widget>[
      SliverAppBar(
        backgroundColor: Colors.white,
        automaticallyImplyLeading: true,
        centerTitle: true,
        title: Text(
          '详情',
          style: TextStyle(fontSize: 18),
        ),
        pinned: true,
        actions: <Widget>[
          IconButton(icon: Icon(Icons.more_vert), onPressed: () {})
        ],
      ),
      _goodInfoWidget(),
      _goodsImgWidget(),
      SliverToBoxAdapter(child: SizedBox(height: 10)),
      SliverToBoxAdapter(child: Container(color: Color(0xffdddddd), height: 1)),
      _userInfoWidget(),
      SliverToBoxAdapter(child: Container(color: Color(0xffdddddd), height: 8)),
      _replyBarWidget(),
      SliverToBoxAdapter(child: Container(color: Color(0xffEEEEEE), height: 1)),
      _replyListWidget(),
    ];
  }

  ///商品详情
  Widget _goodInfoWidget() {
    return SliverToBoxAdapter(
      child: Container(
        padding: EdgeInsets.all(10),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            Text(
              null == goods ? "" : goods.goodsName,
              style: TextStyle(
                fontSize: 16,
                fontWeight: FontWeight.w600,
              ),
            ),
            Text(
              null == goods ? "" : goods.goodsInfo,
              style: TextStyle(
                fontSize: 16,
                fontWeight: FontWeight.w500,
              ),
            ),
          ],
        ),
      ),
    );
  }

  ///商品图片
  Widget _goodsImgWidget() {
    bool showPic =
        null != goods && null != goods.goodsImg && goods.goodsImg.isNotEmpty;
    Widget picWidget;
    if (!showPic) {
      return SliverToBoxAdapter(
          child: Container(color: Colors.white, height: 8));
    } else {
      List<String> images = goods.goodsImg.split(",");
      List<Widget> childs = images.map((item) {
        BorderRadius borderRadius;
        if (images.length == 1) {
          borderRadius = BorderRadius.circular(6);
        } else if (item == images.first) {
          borderRadius = BorderRadius.only(
              topLeft: Radius.circular(6),
              topRight: Radius.circular(6),
              bottomLeft: Radius.circular(0),
              bottomRight: Radius.circular(0));
        } else if (item == images.last) {
          borderRadius = BorderRadius.only(
              topLeft: Radius.circular(0),
              topRight: Radius.circular(0),
              bottomLeft: Radius.circular(6),
              bottomRight: Radius.circular(6));
        } else {
          borderRadius = BorderRadius.circular(0);
        }
        double picWidth = MediaQuery.of(context).size.width - 20;
        return GestureDetector(
            child: Container(
              width: picWidth,
              margin: EdgeInsets.only(bottom: 10),
              child: ClipRRect(
                borderRadius: borderRadius,
                child: CachedNetworkImage(
                  imageUrl: Api.getUrl(item),
                  fit: BoxFit.cover,
                  errorWidget: (context, url, error) => CommWidget.imgError(),
                ),
              ),
            ),
            onTap: () {
              int current = images.indexOf(item);
              Navigator.of(context).push(
                RouteSlide(
                  ImagePage(images, current: current),
                ),
              );
            });
      }).toList();
      picWidget = Column(
          mainAxisAlignment: MainAxisAlignment.spaceBetween, children: childs);
      return SliverToBoxAdapter(
        child: picWidget,
      );
    }
  }

  ///发布作者
  Widget _userInfoWidget() {
    return SliverToBoxAdapter(
      child: GestureDetector(
        onTap: () {
          Routers.router.navigateTo(
              context, '${Routers.PAGE_USERINFO}?userId=${goods.userId}',
              transition: TransitionType.inFromRight);
        },
        child: Row(children: <Widget>[
          Container(
            width: 36,
            height: 36,
            margin: EdgeInsets.all(10),
            child: ClipOval(
              child: CachedNetworkImage(
                imageUrl: Api.getUrl(null == goods ? "" : goods.imgUrl),
                fit: BoxFit.cover,
                errorWidget: (context, url, error) => Image.asset(
                  Comm.IMG_DEFAULT,
                  fit: BoxFit.cover,
                ),
              ),
            ),
          ),
          Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                null != goods && null != goods.userName
                    ? Text(
                        goods.userName,
                        style: TextStyle(
                          fontSize: 14,
                          fontWeight: FontWeight.bold,
                        ),
                      )
                    : Container(),
                Text(
                  '${CommUtil.getTimeDiff(null == goods ? null : goods.createAt)} ${null != goods && null != goods.address ? "发布于${goods.address}" : ""}',
                  style: TextStyle(color: Colors.grey, fontSize: 12),
                )
              ])
        ]),
      ),
    );
  }

  ///留言标题栏
  Widget _replyBarWidget() {
    Widget _replyBtn = GestureDetector(
      child: Container(
        height: 28,
        alignment: Alignment.center,
        padding: EdgeInsets.only(left: 4, right: 4),
        decoration: BoxDecoration(
            border: Border.all(color: Colors.deepOrange, width: 1),
            borderRadius: BorderRadius.circular(4)),
        child: Row(children: <Widget>[
          Icon(
            Icons.edit,
            size: 14,
            color: Colors.deepOrange,
          ),
          Text(
            '写留言',
            style: TextStyle(color: Colors.deepOrange),
          )
        ]),
      ),
      onTap: () {
        setState(() {
          _isEdit = !_isEdit;
        });
      },
    );
    return SliverToBoxAdapter(
      child: Container(
        padding: EdgeInsets.all(10),
        child: Row(children: <Widget>[
          Text('最新留言', style: TextStyle(fontSize: 16)),
          Expanded(child: Container()),
          _replyBtn,
        ]),
      ),
    );
  }

  ///留言列表
  Widget _replyListWidget() {
    if (_item.isEmpty) {
      return SliverToBoxAdapter(
        child: CommWidget.nullWidget(msg: '还没有人评论,还不快来抢沙发~'),
      );
    } else {
      return SliverList(
          delegate:
              SliverChildBuilderDelegate((BuildContext context, int index) {
        GdsMsg gdsMsg = _item[index];
        return _itemGdsMsgWidget(gdsMsg);
      }, childCount: _item.length));
    }
  }

  ///留言列表item
  Widget _itemGdsMsgWidget(GdsMsg gdsMsg) {
    return Container(
      margin: EdgeInsets.all(10),
      child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          mainAxisSize: MainAxisSize.max,
          children: <Widget>[
            Row(children: <Widget>[
              GestureDetector(
                  child: Row(children: <Widget>[
                    Container(
                      width: 30,
                      height: 30,
                      margin: EdgeInsets.only(bottom: 6),
                      child: ClipOval(
                        child: CachedNetworkImage(
                          imageUrl: Api.getUrl(gdsMsg.imgUrl),
                          fit: BoxFit.cover,
                          errorWidget: (context, url, error) => Image.asset(
                            Comm.IMG_DEFAULT,
                            fit: BoxFit.cover,
                          ),
                        ),
                      ),
                    ),
                    Container(
                        margin: EdgeInsets.only(left: 6, bottom: 6),
                        child: Text(gdsMsg.userName,
                            style: TextStyle(fontWeight: FontWeight.bold)))
                  ]),
                  onTap: () {
                    Routers.router.navigateTo(context,
                        '${Routers.PAGE_USERINFO}?userId=${gdsMsg.userId}',
                        transition: TransitionType.inFromRight);
                  }),
              _isSelf
                  ? Container(
                      margin: EdgeInsets.only(bottom: 6, left: 4),
                      padding: EdgeInsets.only(left: 2, right: 2),
                      decoration: BoxDecoration(
                          border: Border.all(
                              color: Theme.of(context).accentColor, width: 0.5),
                          borderRadius: BorderRadius.circular(2)),
                      child: Text(
                        '作者',
                        style: TextStyle(
                            color: Theme.of(context).accentColor, fontSize: 10),
                      ),
                    )
                  : Container()
            ]),
            Container(
                margin: EdgeInsets.only(left: 36), child: Text(gdsMsg.content)),
            Container(
              margin: EdgeInsets.only(left: 36, top: 6),
              child: Text(CommUtil.getTimeDiff(gdsMsg.createAt),
                  style: TextStyle(color: Color(0xffaaaaaa))),
            )
          ]),
    );
  }

  ///底部悬浮栏
  Widget _bottomSheet() {
    if (_isSelf) {
      return Container();
    }
    return Container(
      height: 49,
      child: Column(children: <Widget>[
        Divider(height: 1, color: Color(0xffdddddd)),
        Row(children: <Widget>[
          Container(
              margin: EdgeInsets.only(left: 10, right: 10),
              child: Column(
                  children: <Widget>[Icon(Icons.favorite_border), Text('收藏')])),
          Container(
              height: 48,
              width: 1,
              margin: EdgeInsets.only(right: 10),
              color: Color(0xffdddddd)),
          Expanded(
              child: Text.rich(TextSpan(children: <TextSpan>[
            TextSpan(
                style: TextStyle(color: Colors.deepOrange, fontSize: 24),
                text: '￥${null == goods ? 0.00 : goods.price}'),
            TextSpan(
                style: TextStyle(color: Colors.deepOrange, fontSize: 24),
                text: '/'),
            _showDisPrice(),
          ]))),
          Container(
            width: 80,
            height: 48,
            color: Colors.deepOrange,
            child: FlatButton(
              onPressed: () {
                User myUser = Provide.value<User>(context);
                if (null == myUser || null == myUser.userId) {
                  Toast.show("请先登录");
                  return;
                }
                var jsons =
                    jsonEncode(Utf8Encoder().convert(json.encode(goods)));
                String url =
                    '${Routers.PAGE_CHAT}?user=$jsons&msgTag=${goods.goodsId}';
                Routers.router.navigateTo(context, url,
                    transition: TransitionType.inFromRight);
              },
              child: Text('我想要', style: TextStyle(color: Colors.white)),
            ),
          )
        ])
      ]),
    );
  }

  ///原价显示
  TextSpan _showDisPrice() {
    TextStyle style;
    String str;
    if (null == goods) {
      return TextSpan(text: "0.00");
    }
    if (null == goods.disPrice) {
      style = TextStyle(color: Colors.deepOrange, fontSize: 12);
      str = '一口价';
    } else {
      style = TextStyle(
          color: Colors.deepOrange,
          fontSize: 12,
          decoration: TextDecoration.lineThrough);
      str = '原价${goods.disPrice}';
    }
    return TextSpan(style: style, text: str);
  }

  ///留言输入框
  Widget _showSendWidget() {
    return Container(
      color: Color(0xffF7F7F7),
      padding: EdgeInsets.only(left: 10, right: 10, top: 10, bottom: 10),
      child: Container(
        alignment: Alignment.centerLeft,
        constraints: BoxConstraints(maxHeight: 144, minHeight: 64),
        padding: EdgeInsets.only(left: 10),
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(22),
          color: Colors.white,
        ),
        child: TextField(
          autofocus: true,
          maxLines: null,
          controller: textController,
          decoration: InputDecoration(
            suffixIcon: IconButton(
                icon: Icon(Icons.send),
                onPressed: () {
                  _addReply();
                }),
            border: OutlineInputBorder(borderSide: BorderSide.none),
            hintText: '输入留言',
            contentPadding: EdgeInsets.all(10),
          ),
        ),
      ),
    );
  }

  ///添加留言
  void _addReply() async {
    if (textController.text.isEmpty) {
      Toast.show("内容不能为空");
      return;
    }
    setState(() {
      _isEdit = false;
    });
    CancelFunc closeLoading = Toast.loading("留言中...");
    Map<String, String> params = Map();
    params['goodsId'] = goods.goodsId;
    params['content'] = textController.text;

    Http.post(Api.URL_GDSMSG_ADD, params: params, successCallBack: (data) {
      closeLoading();
      _getReply();
      setState(() {
        textController.value = TextEditingValue(text: '');
      });
    }, errorCallBack: (msg) {
      closeLoading();
      Toast.show(msg);
    });
  }

  void _getGoods() {
    String url = '${Api.URL_GOODSINFO}?goodsId=${widget.goodsId}';
    Http.get(url, successCallBack: (data) {
      print('留言内容：$data');
      setState(() {
        goods = Goods.fromJson(json.decode(data));
        _isSelf = null != user && user.userId == goods.userId;
      });
    }, errorCallBack: (msg) {
      Toast.show(msg);
    });
  }

  ///获取回复内容
  void _getReply() async {
    String url = '${Api.URL_GDSMSG_LIST}?goodsId=${widget.goodsId}';
    Http.get(url, successCallBack: (data) {
      print('留言内容：$data');
      List list = json.decode(data).map((m) => GdsMsg.fromJson(m)).toList();
      _item.clear();
      setState(() {
        _item.addAll(list);
      });
    }, errorCallBack: (msg) {
      Toast.show(msg);
    });
  }
}
